﻿<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

using CE.Database;
public class Handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Clear();

        if (context.Request["fileName"] != null && context.Request["carId"] != null)
        {
            MyDatabase _db = new MyDatabase();
            string _filePath = "";
            string _carId = context.Request["carId"].ToString();
            object _objFilePath = _db.ExecuteScalarSqlStatement("Select Info1 from tblReferenceCEUser Where ProductId = " + _carId + " And ProductType = 'CI' And Status = 1");
            if (_objFilePath != null)
            {
                _filePath = Convert.ToString(_objFilePath);
                string fileName = context.Request.QueryString["fileName"].ToString();
                
                //string filePath = HttpContext.Current.Server.MapPath("~/downloads/" + fileName);
                string filePath = _filePath; //context.Request.QueryString["filePath"].ToString();
                //_filePath = _filePath.Replace(".xls", ".htm");
                //Be sure the file exists
                FileInfo file = new System.IO.FileInfo(filePath);
                if (!file.Exists)
                {
                    context.Response.StatusCode = 500;
                    context.Response.End();
                    return;
                }
                //fileName = file.Name.Replace(".xls", ".htm");
                context.Response.Clear();
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.Cache.SetNoStore();
                context.Response.Cache.SetExpires(DateTime.MinValue);
                //The next few lines is what actually starts downloads the file.
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                context.Response.AddHeader("Content-Length", file.Length.ToString());
                context.Response.ContentType = "application/octet-stream";
                context.Response.WriteFile(file.FullName);
                context.ApplicationInstance.CompleteRequest();
                context.Response.End();
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}